package top.lyjwn.todo.resources.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.lyjwn.todo.resources.config.ResourcesConfig;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 文件工具
 *
 * @author luoyujie
 */
public class FileUtil {

    private final static Logger log = LoggerFactory.getLogger("error");
    private final static Logger infoLog = LoggerFactory.getLogger("info");

    public static boolean write(String name, byte[] bytes) {
        RandomAccessFile raf = null;
        try {
            File file = new File(ResourcesConfig.store_path);
            if (!file.exists()) {
                file.mkdirs();
            }
            raf = new RandomAccessFile(ResourcesConfig.store_path + name, "rw");
        } catch (FileNotFoundException e) {
            log.error("没有找到对应资源", e);
        }
        if (raf != null) {
            try {
                raf.setLength(0);
                raf.write(bytes);
                return true;
            } catch (IOException e) {
                log.error("写入失败", e);
            }
        }
        return false;
    }

    public static boolean read(OnFileOut out, String name) {
        RandomAccessFile aFile = null;
        try {
            aFile = new RandomAccessFile(ResourcesConfig.store_path + name, "r");
            byte[] buf = new byte[1024];
            while ((aFile.read(buf)) != -1) {
                out.out(buf);
            }
            return true;
        } catch (FileNotFoundException e) {
            log.error("找不到指定的文件====>>>  " + e.getMessage());
        } catch (IOException e) {
            log.error("读取失败====>>>  " + name, e);
        }
        return false;
    }


    public static boolean delete(String name) {
        boolean result = false;
        File file = new File(name);
        if (file.exists()) {
            file.delete();
            result = true;
            infoLog.info("已删除资源" + name);
        }
        return result;

    }

    /**
     * 文件输出
     */
    public interface OnFileOut {
        void out(byte[] bytes) throws IOException;
    }

}
